<template>
  <el-dialog
    width="600px"
    :visible="visible"
    :title="'OTDR' + $t('TIME_DETECT')"
    @open="open"
    @close="close"
  >
    <el-form ref="otdrParam" :model="otdrParam" :rules="rules" label-width="auto" class="pr-10">
      <el-form-item :label="$t('TEST_NAME')" prop="planName">
        <el-input
          v-model.trim="otdrParam.planName"
          maxlength="32"
          :readonly="operateType === 'view'"
        />
      </el-form-item>
      <el-form-item :label="$t('TEST_CYCLE')" prop="gapDay">
        <el-select
          v-model="otdrParam.gapDay"
          placeholder=""
          style="width: 290px"
          class="fl mr-10"
          :disabled="operateType !== 'add' && operateType !== 'copy'"
          filterable
          allow-create
          default-first-option
        >
          <el-option label="7" :value="7" />
          <el-option label="30" :value="30" />
          <el-option label="60" :value="60" />
          <el-option label="90" :value="90" />
          <el-option label="180" :value="180" />
        </el-select>
        {{ $t('UNIT_DAY') }}
      </el-form-item>
      <el-form-item :label="$t('TEST_PERIOD')" required>
        <div class="flex justify-between w-100">
          <el-form-item label-width="0" prop="startTime" class="flex-1 mr-5">
            <el-time-picker
              v-model="otdrParam.startTime"
              :disabled="operateType === 'view'"
              style="width: 100%"
              format="HH:mm"
              value-format="HH:mm:00"
              :placeholder="$t('START_TIME')"
              :clearable="false"
            />
          </el-form-item>
          <span>-</span>
          <el-form-item label-width="0" prop="endTime" class="flex-1 ml-5">
            <el-time-picker
              v-model="otdrParam.endTime"
              :disabled="operateType === 'view'"
              style="width: 100%"
              format="HH:mm"
              value-format="HH:mm:00"
              :placeholder="$t('END_TIME')"
              :clearable="false"
            />
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item :label="$t('TEST_TIME')" required>
        <div class="flex justify-between w-100">
          <el-form-item label-width="0" prop="startDate" class="flex-1 mr-5">
            <el-date-picker
              v-model="otdrParam.startDate"
              size="mini"
              type="date"
              style="width: 100%"
              :disabled="operateType !== 'add' && operateType !== 'copy'"
              :placeholder="$t('START_DATE')"
              value-format="yyyy-MM-dd"
              :picker-options="startPickerOptions"
            />
          </el-form-item>
          <span>-</span>
          <el-form-item label-width="0" prop="endDate" class="flex-1" style="margin: 0 0 0 5px">
            <el-date-picker
              v-model="otdrParam.endDate"
              size="mini"
              type="date"
              style="width: 100%"
              :disabled="operateType === 'view'"
              :placeholder="$t('END_DATE')"
              value-format="yyyy-MM-dd"
              :picker-options="endPickerOptions"
            />
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item :label="$t('DESCRIPTION')">
        <el-input
          v-model.trim="otdrParam.description"
          :readonly="operateType === 'view'"
          type="textarea"
          :row="4"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button v-if="operateType != 'view'" type="primary" @click="$debounce(save)">{{
        $t('SAVE')
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { timeToSec, formatDate } from '@/utils/common'
  import linkTestPlan from '@/api/oen/LinkTestPlan'

  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      operateType: {
        type: String,
        default: ''
      },
      formData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        otdrParam: {
          spanDay: false,
          planName: '',
          description: '',
          endDate: null,
          endTime: null,
          startTime: null,
          startDate: null,
          gapDay: null
        },
        startPickerOptions: {
          disabledDate: time => {
            let disabled = time.getTime() < new Date().getTime() - 86400 * 1000
            if (this.otdrParam.endDate) {
              disabled = time.getTime() > new Date(this.otdrParam.endDate).getTime() || disabled
            }
            return disabled
          }
        },
        endPickerOptions: {
          disabledDate: time => {
            let disabled = time.getTime() < new Date().getTime() - 86400 * 1000
            if (this.otdrParam.startDate) {
              disabled =
                time.getTime() < new Date(this.otdrParam.startDate).getTime() - 86400 * 1000 ||
                disabled
            }
            return disabled
          }
        }
      }
    },
    computed: {
      ...mapGetters(['dictList']),
      rules() {
        return {
          planName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('TEST_NAME'),
              trigger: 'blur'
            }
          ],
          gapDay: [
            {
              required: true,
              validator: (rule, value, callback) => {
                this.validatePort(rule, value, callback)
              },
              trigger: ['blur', 'change']
            }
          ],
          startTime: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('START_TIME'),
              trigger: 'change'
            }
          ],
          endTime: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('END_TIME'),
              trigger: 'change'
            }
          ],
          startDate: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('START_DATE'),
              trigger: 'change'
            }
          ],
          endDate: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('END_DATE'),
              trigger: 'change'
            }
          ]
        }
      }
    },
    methods: {
      validatePort(rule, value, callback) {
        if (Number(value) > 9999 || Number(value) < 1) {
          callback(
            new Error(
              this.$t('RANGE_MSG_ERROR', {
                msg: '1 - 9999'
              })
            )
          )
        } else {
          callback()
        }
      },
      open() {
        console.log('this.formData', this.formData)
        if (this.operateType === 'add') {
          this.otdrParam = this.$options.data().otdrParam
        } else {
          let startDate = this.formData.startDate
          let endDate = this.formData.endDate
          let planName = this.formData.planName
          if (this.operateType === 'copy') {
            planName = ''
            if (new Date(this.formData.startDate).getTime() < new Date().getTime() - 86400 * 1000) {
              startDate = ''
            }
            if (new Date(this.formData.endDate).getTime() < new Date().getTime() - 86400 * 1000) {
              endDate = ''
            }
          }
          this.otdrParam = {
            spanDay: this.formData.spanDay,
            planName: planName,
            description: this.formData.description,
            endDate: endDate,
            endTime: this.formData.endTime,
            startTime: this.formData.startTime,
            startDate: startDate,
            gapDay: this.formData.gapDay
          }
        }
        this.$nextTick(() => {
          this.$refs.otdrParam && this.$refs.otdrParam.clearValidate()
        })
      },
      // 保存
      save() {
        this.$refs.otdrParam.validate(valid => {
          if (!valid) return
          const startTime = timeToSec(this.otdrParam.startTime)
          const nowTime = timeToSec(formatDate(new Date(), 'hh:mm:ss'))
          if (
            startTime <= nowTime &&
            this.otdrParam.startDate === formatDate(new Date(), 'yyyy-MM-dd')
          ) {
            this.$confirm(this.$t('TIME_PASSED'), {
              confirmButtonText: this.$t('CONTINUE'),
              cancelButtonText: this.$t('CANCEL'),
              type: 'warning'
            })
              .then(() => {
                this.submit()
              })
              .catch(() => {})
          } else {
            this.submit()
          }
        })
      },
      submit() {
        this.otdrParam.gapDay = String(this.otdrParam.gapDay).trim()
        // console.log('this.formData.gapDay', this.otdrParam.gapDay)
        if (!/^[1-9]\d*$/g.test(this.otdrParam.gapDay)) {
          this.$message.error(this.$t('TEST_CYCLE') + '：' + this.$t('ONLY_INT'))
          return
        }
        const startTime = timeToSec(this.otdrParam.startTime)
        const endTime = timeToSec(this.otdrParam.endTime)
        // 测试时间选择同一天判断1.不能跨天测试，2.如果是是当天，不能选择当前时间之前
        if (this.otdrParam.startDate === this.otdrParam.endDate) {
          if (startTime > endTime) {
            this.$message.error(this.$t('ONEDAY_CANNOT_CROSS'))
            return
          }
        }

        // 比较测试时段必须相差30分钟以上 跨天结束时间加一天（24*60*60）
        this.otdrParam.spanDay = startTime > endTime
        console.log('startTime', startTime)
        console.log('endTime', endTime)
        if (
          (!this.otdrParam.spanDay && startTime > endTime - 30 * 60) ||
          (this.otdrParam.spanDay && startTime + 30 * 60 > endTime + 24 * 60 * 60)
        ) {
          this.$message.error(this.$t('TEST_TIME_RANGE'))
          return
        }
        // 组装stepList参数
        const deviceIds = {}
        this.formData.portList.forEach(i => {
          if (!deviceIds[i.deviceId]) {
            deviceIds[i.deviceId] = {
              deviceId: i.deviceId,
              deviceName: i.deviceName,
              portList: [i.portId],
              testDirection: i.testDirection
            }
          } else {
            deviceIds[i.deviceId].portList.push(i.portId)
          }
        })
        const requestData = {
          ...this.otdrParam,
          stepList: Object.values(deviceIds),
          segmentName: this.formData.segmentName,
          physicStruct: this.formData.physicStruct,
          startNodeId: this.formData.startNodeId,
          endNodeId: this.formData.endNodeId,
          linkSegmentId: this.formData.segmentId,
          segmentId: this.formData.segmentId,
          portList: this.formData.portList,
          operateType: this.operateType // 操作日志需要此参数
        }
        if (this.operateType === 'add' || this.operateType === 'copy') {
          linkTestPlan.add(requestData).then(res => {
            this.$message.success(this.$t('ADD_SUCCESS'))
            this.close(true)
          })
        } else {
          requestData.id = this.formData.id
          requestData.planId = this.formData.planId
          linkTestPlan.mod(requestData).then(res => {
            this.$message.success(this.$t('MODIFY_SUCCESS'))
            this.close(true)
          })
        }
      },
      close(load) {
        this.$refs.otdrParam.clearValidate()
        this.$emit('close', load)
      }
    }
  }
</script>

<style scoped></style>
